package com.yyh.synctool.client.tool;

import com.yyh.common.Common;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

/**
 * @author xuan
 * @create 2021/12/11
 */
public abstract class Config
{
    private Properties properties;

    protected Config() {
    }

    public String show() {
        return properties.toString();
    }

    /** 键不存在时返回空串 */
    public String getProperty(String key) {
        return properties.getProperty(key, "");
    }

    /** 设置并持久化*/
    public String setProperty(String key, String value) {
        // 设置Properties属性不能为空值
        String ret = (String) properties.setProperty(key, null == value ? "" : value);
        return ret;
    }

    protected void load() {
        this.properties = new Properties();
        try(
            FileReader fileReader = new FileReader(getFilePath())
        ) {
            this.properties.load(fileReader);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    protected void store() {
        String comments = "update: " + Common.currentTime();
        try(
            FileWriter fileWriter = new FileWriter(getFilePath())
        ) {
            properties.store(fileWriter, comments);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /** 操作平台上文件的 绝对路径 */
    abstract protected File getFilePath() throws IOException;
}
